<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/java-notes/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/java-notes/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/java-notes/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/java-notes/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/java-notes/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/java-notes/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/java-notes/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaSE,Concurrent,Atomic,Thread," />










<meta name="description" content="Java并发基础知识、面试题以及Concurrent包下工具使用。">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程-基础&amp;工具">
<meta property="og:url" content="https://hitomeng.gitee.io/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/index.html">
<meta property="og:site_name" content="JavaNote">
<meta property="og:description" content="Java并发基础知识、面试题以及Concurrent包下工具使用。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/concurrent-hashmap.png">
<meta property="og:image" content="https://hitomeng.gitee.io/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/.%5CJava%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7%5Cconcurrent-hashmap.png">
<meta property="og:image" content="https://gblobscdn.gitbook.com/assets%2F-L_5HvtIhTFW9TQlOF8e%2F-L_5TIKcBFHWPtY3OwUo%2F-L_5TJw4VyRYbSwAlVTD%2Ffork_join%E6%B5%81%E7%A8%8B%E5%9B%BE.png?alt=media">
<meta property="article:published_time" content="2020-05-25T15:06:04.000Z">
<meta property="article:modified_time" content="2020-06-03T14:44:00.437Z">
<meta property="article:author" content="HitoMeng">
<meta property="article:tag" content="JavaSE">
<meta property="article:tag" content="Concurrent">
<meta property="article:tag" content="Atomic">
<meta property="article:tag" content="Thread">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://hitomeng.gitee.io/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/concurrent-hashmap.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/java-notes/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://hitomeng.gitee.io/2020/05/25/Java并发编程-基础-工具/"/>





  <title>Java并发编程-基础&工具 | JavaNote</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/java-notes/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">JavaNote</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">To be a better developer!</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/java-notes/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/java-notes/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/java-notes/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/java-notes/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/java-notes/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://hitomeng.gitee.io/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HitoMeng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/java-notes/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JavaNote">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发编程-基础&工具</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2020-05-25T23:06:04+08:00">
                2020-05-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/java-notes/categories/High-Concurrent/" itemprop="url" rel="index">
                    <span itemprop="name">High Concurrent</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Java并发基础知识、面试题以及Concurrent包下工具使用。</p>
<a id="more"></a>

<h2 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a>基础知识</h2><h3 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h3><ol>
<li><p>进程与线程的区别</p>
<p> 进程是操作系统进行资源分配的基本单位，而线程是操作系统进行调度的基本单位.</p>
<ul>
<li>进程单独占有一定的内存地址空间，所以进程间存在内存隔离，数据是分开的，<strong>数据共享复杂</strong>但是同步简单，各个进程之间互不干扰；而线程共享所属进程占有的内存地址空间和资源，<strong>数据共享简单</strong>，但是同步复杂。</li>
<li>进程单独占有一定的内存地址空间，一个进程出现问题<strong>不会影响其他进程</strong>，不影响主程序的稳定性，可靠性高；<strong>一个线程崩溃可能影响整个程序的稳定性</strong>，可靠性较低。  </li>
<li>进程单独占有一定的内存地址空间，进程的创建和销毁不仅需要保存寄存器和栈信息，<strong>还需要资源的分配回收以及页调度，开销较大</strong>；线程只需要保存寄存器和栈信息，开销较小。 </li>
</ul>
</li>
<li><p>上下文切换</p>
<p>上下文切换（有时也称做进程切换或任务切换）是指 CPU 从一个进程（或线程）切换到另一个进程（或线程）。上下文是指<strong>某一时间点 CPU 寄存器和程序计数器的内容。</strong> </p>
</li>
</ol>
<h3 id="入门类及接口"><a href="#入门类及接口" class="headerlink" title="入门类及接口"></a>入门类及接口</h3><ol>
<li><p>Thread类与Runnable接口的比较 </p>
<ul>
<li><p>由于Java“单继承，多实现”的特性，Runnable接口使用起来比Thread更灵活。</p>
</li>
<li><p>Runnable接口出现更符合面向对象，将线程单独进行对象的封装。</p>
</li>
<li><p>Runnable接口出现，降低了线程对象和线程任务的耦合性。</p>
</li>
<li><p>如果使用线程时不需要使用Thread类的诸多方法，显然使用Runnable接口更为轻量。</p>
</li>
</ul>
<p>我们通常优先使用“实现<code>Runnable</code>接口”这种方式来自定义线程类。 </p>
</li>
<li><p>Callable、Future与FutureTask </p>
<p><code>Callable</code>与<code>Runnable</code>类似，同样是只有一个抽象方法的函数式接口。不同的是，<code>Callable</code>提供的方法是<strong>有返回值</strong>的，而且支持<strong>泛型</strong>。  <code>Callable</code>一般是配合线程池工具<code>ExecutorService</code>来使用的,<code>ExecutorService</code>可以使用<code>submit</code>方法来让一个<code>Callable</code>接口执行。它会返回一个<code>Future</code>，我们后续的程序可以通过这个<code>Future</code>的<code>get</code>方法得到结果。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">interface</span> <span class="title">Future</span>&lt;<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">cancel</span><span class="params">(<span class="keyword">boolean</span> paramBoolean)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">isCancelled</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">isDone</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> V <span class="title">get</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException, ExecutionException</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> V <span class="title">get</span><span class="params">(<span class="keyword">long</span> paramLong, TimeUnit paramTimeUnit)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> InterruptedException, ExecutionException, TimeoutException</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>Thread类的几个常用方法</p>
<ul>
<li><p>currentThread()：静态方法，返回对当前正在执行的线程对象的引用；</p>
</li>
<li><p>start()：开始执行线程的方法，java虚拟机会调用线程内的run()方法；</p>
</li>
<li><p>yield()：yield在英语里有放弃的意思，同样，这里的yield()指的是当前线程愿意让出对当前处理器的占用。这里需要注意的是，就算当前线程调用了yield()方法，程序在调度的时候，也还有可能继续运行这个线程的；</p>
</li>
<li><p>sleep()：静态方法，使当前线程睡眠一段时间，不释放锁；</p>
</li>
<li><p>join()：使当前线程等待另一个线程执行完毕之后再继续执行，内部调用的是Object类的wait方法实现的；</p>
</li>
</ul>
<p>Object类中与线程有关的方法：</p>
<ul>
<li><p><strong>wait()</strong>  ：让执行的当前线程休息一下，后面需要再唤醒。释放了该Object的monitor锁 </p>
<ul>
<li>线程拥有monitor锁才能用wait方法，执行后会放弃锁</li>
<li>必须在synchronize修饰的方法或代码块中</li>
</ul>
</li>
<li><p><strong>notify(), notifyAll()</strong> :  唤醒该Object上wait的线程， notify是随机唤醒一个，notifyAll唤醒所有。 </p>
<p>必须在synchronize修饰的方法或代码块中，拥有该monitor，才能执行notify  <strong>注意： 因为进行唤醒的方法notify执行完后，还持有monitor，所以被唤醒wait的线程不能立即获取锁，状态从waiting变成了blocked</strong> </p>
</li>
</ul>
</li>
<li><p>wait和notify为什么定义在Object中，sleep定义在Thread中？ </p>
<p>因为wait和notify涉及到锁的获取释放，锁是对象的。经常会有线程持有多个对象的锁来进行配合。 </p>
</li>
<li><p>wait和sleep方法的异同 </p>
<p>同: 都可以使线程阻塞进入waiting或timedwaiting状态； 都可以响应中断，并抛出异常并清除中断状态</p>
<p>异: wait需要在同步代码块中；wait可以不用参数永久等待，直到被中断或唤醒notify；wait会释放monitor锁，sleep不会释放锁；wait，notify是Object方法， sleep是Thread方法</p>
</li>
</ol>
<h3 id="线程状态转换"><a href="#线程状态转换" class="headerlink" title="线程状态转换"></a>线程状态转换</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Thread.State 源码</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> State &#123;</span><br><span class="line">    NEW,</span><br><span class="line">    RUNNABLE,</span><br><span class="line">    BLOCKED,</span><br><span class="line">    WAITING,</span><br><span class="line">    TIMED_WAITING,</span><br><span class="line">    TERMINATED;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li><p>NEW</p>
<p> 处于NEW状态的线程此时尚未启动。这里的尚未启动指的是还没调用Thread实例的start()方法。 </p>
<ul>
<li><p><strong>反复调用同一个线程的start()方法是否可行？</strong></p>
</li>
<li><p><strong>假如一个线程执行完毕（此时处于TERMINATED状态），再次调用这个线程的start()方法是否可行？</strong></p>
</li>
</ul>
<blockquote>
<p>两个问题的答案都是不可行，在调用一次start()之后，threadStatus的值会改变（threadStatus !=0），此时再次调用start()方法会抛出IllegalThreadStateException异常。 </p>
</blockquote>
</li>
<li><p>RUNNABLE</p>
<p> 表示当前线程正在运行中 </p>
</li>
<li><p>BLOCKED</p>
<p> 阻塞状态。处于BLOCKED状态的线程正<strong>等待锁的释放</strong>以进入同步区。 </p>
</li>
<li><p>WAITING</p>
<p>等待状态。处于等待状态的线程变成RUNNABLE状态需要其他线程唤醒，再次参与锁竞争后才能执行 </p>
<p>调用如下3个方法会使线程进入等待状态：</p>
<ul>
<li>Object.wait()：使当前线程处于等待状态直到另一个线程唤醒它；</li>
<li>Thread.join()：等待线程执行完毕，底层调用的是Object实例的wait方法；</li>
<li>LockSupport.park()：除非获得调用许可，否则禁用当前线程进行线程调度。</li>
</ul>
</li>
<li><p>TIMED_WAITING</p>
<p>超时等待状态。线程等待一个具体的时间，时间到后会被自动唤醒。 </p>
<p>调用如下方法会使线程进入超时等待状态：</p>
<ul>
<li>Thread.sleep(long millis)：使当前线程睡眠指定时间；</li>
<li>Object.wait(long timeout)：线程休眠指定时间，等待期间可以通过notify()/notifyAll()唤醒；</li>
<li>Thread.join(long millis)：等待当前线程最多执行millis毫秒，如果millis为0，则会一直执行；</li>
<li>LockSupport.parkNanos(long nanos)： 除非获得调用许可，否则禁用当前线程进行线程调度指定时间；</li>
<li>LockSupport.parkUntil(long deadline)：同上，也是禁止线程进行调度指定时间；</li>
</ul>
</li>
<li><p>TERMINATED</p>
<p> 终止状态。此时线程已执行完毕。 </p>
</li>
</ol>
<h3 id="线程间通讯"><a href="#线程间通讯" class="headerlink" title="线程间通讯"></a>线程间通讯</h3><ol>
<li><p>锁与同步 </p>
</li>
<li><p>等待/通知机制 </p>
</li>
<li><p>信号量（eg： volatile 读写锁）</p>
</li>
<li><p>管道</p>
<p> 管道是基于“管道流”的通信方式。JDK提供了<code>PipedWriter</code>、 <code>PipedReader</code>、 <code>PipedOutputStream</code>、 <code>PipedInputStream</code>。其中，前面两个是基于字符的，后面两个是基于字节流的。 </p>
</li>
</ol>
<h2 id="工具"><a href="#工具" class="headerlink" title="工具"></a>工具</h2><h4 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h4><p>使用线程池主要有以下三个原因：</p>
<ol>
<li>创建/销毁线程需要消耗系统资源，线程池可以<strong>复用已创建的线程</strong>。</li>
<li><strong>控制并发的数量</strong>。并发数量过多，可能会导致资源消耗过多，从而造成服务器崩溃。（主要原因）</li>
<li><strong>可以对线程做统一管理</strong>。</li>
</ol>
<h5 id="线程池原理"><a href="#线程池原理" class="headerlink" title="线程池原理"></a>线程池原理</h5><ol>
<li><p>构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 最长的七个参数的构造函数</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                          <span class="keyword">int</span> maximumPoolSize,</span></span></span><br><span class="line"><span class="function"><span class="params">                          <span class="keyword">long</span> keepAliveTime,</span></span></span><br><span class="line"><span class="function"><span class="params">                          TimeUnit unit,</span></span></span><br><span class="line"><span class="function"><span class="params">                          BlockingQueue&lt;Runnable&gt; workQueue,</span></span></span><br><span class="line"><span class="function"><span class="params">                          ThreadFactory threadFactory,</span></span></span><br><span class="line"><span class="function"><span class="params">                          RejectedExecutionHandler handler)</span></span></span><br></pre></td></tr></table></figure>

<p>必须参数：</p>
<ul>
<li><strong>int corePoolSize</strong>：该线程池中<strong>核心线程数最大值</strong> </li>
<li><strong>int maximumPoolSize</strong>：该线程池中<strong>线程总数最大值</strong>  </li>
<li><strong>long keepAliveTime</strong>：<strong>非核心线程闲置超时时长</strong> </li>
<li><strong>TimeUnit unit</strong>：keepAliveTime的单位 </li>
<li><strong>BlockingQueue workQueue</strong>：阻塞队列，维护着<strong>等待执行的Runnable任务对象</strong> </li>
</ul>
<p>非必须参数：</p>
<ul>
<li><p><strong>ThreadFactory threadFactory:</strong>  创建线程的工厂 ，用于批量创建线程，统一在创建线程时设置一些参数，如是否守护线程、线程的优先级等。如果不指定，会新建一个默认的线程工厂。 </p>
</li>
<li><p>*<em>RejectedExecutionHandler handler: *</em> </p>
<p><strong>拒绝处理策略</strong>，线程数量大于最大线程数就会采用拒绝处理策略，四种拒绝处理的策略为 ：</p>
<ol>
<li><strong>ThreadPoolExecutor.AbortPolicy</strong>：<strong>默认拒绝处理策略</strong>，丢弃任务并抛出RejectedExecutionException异常。</li>
<li><strong>ThreadPoolExecutor.DiscardPolicy</strong>：丢弃新来的任务，但是不抛出异常。</li>
<li><strong>ThreadPoolExecutor.DiscardOldestPolicy</strong>：丢弃队列头部（最旧的）的任务，然后重新尝试执行程序（如果再次失败，重复此过程）。</li>
<li><strong>ThreadPoolExecutor.CallerRunsPolicy</strong>：由调用线程处理该任务。</li>
</ol>
</li>
</ul>
</li>
<li><p>ThreadPoolExecutor的策略</p>
<p>线程池本身有一个调度线程，这个线程就是用于管理布控整个线程池里的各种任务和事务，例如创建线程、销毁线程、任务队列管理、线程队列管理等等。</p>
<p>故线程池也有自己的状态。<code>ThreadPoolExecutor</code>类中定义了一个<code>volatile int</code>变量<strong>runState</strong>来表示线程池的状态 ，分别为RUNNING、SHURDOWN、STOP、TIDYING 、TERMINATED。</p>
</li>
<li><p>线程池主要的任务处理流程 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// JDK 1.8 </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Runnable command)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (command == <span class="keyword">null</span>)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> NullPointerException();   </span><br><span class="line">    <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">    <span class="comment">// 1.当前线程数小于corePoolSize,则调用addWorker创建核心线程执行任务</span></span><br><span class="line">    <span class="keyword">if</span> (workerCountOf(c) &lt; corePoolSize) &#123;</span><br><span class="line">       <span class="keyword">if</span> (addWorker(command, <span class="keyword">true</span>))</span><br><span class="line">           <span class="keyword">return</span>;</span><br><span class="line">       c = ctl.get();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 2.如果不小于corePoolSize，则将任务添加到workQueue队列。</span></span><br><span class="line">    <span class="keyword">if</span> (isRunning(c) &amp;&amp; workQueue.offer(command)) &#123;</span><br><span class="line">        <span class="keyword">int</span> recheck = ctl.get();</span><br><span class="line">        <span class="comment">// 2.1 如果isRunning返回false(状态检查)，则remove这个任务，然后执行拒绝策略。</span></span><br><span class="line">        <span class="keyword">if</span> (! isRunning(recheck) &amp;&amp; remove(command))</span><br><span class="line">            reject(command);</span><br><span class="line">            <span class="comment">// 2.2 线程池处于running状态，但是没有线程，则创建线程</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (workerCountOf(recheck) == <span class="number">0</span>)</span><br><span class="line">            addWorker(<span class="keyword">null</span>, <span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 3.如果放入workQueue失败，则创建非核心线程执行任务，</span></span><br><span class="line">    <span class="comment">// 如果这时创建非核心线程失败(当前线程总数不小于maximumPoolSize时)，就会执行拒绝策略。</span></span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (!addWorker(command, <span class="keyword">false</span>))</span><br><span class="line">         reject(command);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol>
<li><p>线程总数量 &lt; corePoolSize，无论线程是否空闲，都会新建一个核心线程执行任务（让核心线程数量快速达到corePoolSize，在核心线程数量 &lt; corePoolSize时）。<strong>注意，这一步需要获得全局锁。</strong></p>
</li>
<li><p>线程总数量 &gt;= corePoolSize时，新来的线程任务会进入任务队列中等待，然后空闲的核心线程会依次去缓存队列中取任务来执行（体现了<strong>线程复用</strong>）。 </p>
</li>
<li><p>当缓存队列满了，说明这个时候任务已经多到爆棚，需要一些“临时工”来执行这些任务了。于是会创建非核心线程去执行这个任务。<strong>注意，这一步需要获得全局锁。</strong></p>
</li>
<li><p>缓存队列满了， 且总线程数达到了maximumPoolSize，则会采取上面提到的拒绝策略进行处理。</p>
</li>
</ol>
</li>
<li><p>ThreadPoolExecutor如何做到线程复用的 </p>
<p>ThreadPoolExecutor在创建线程时，会将线程封装成<strong>工作线程worker</strong>,并放入<strong>工作线程组</strong>中，然后这个worker反复从阻塞队列中拿任务去执行。 </p>
<p>execute–&gt; addWorker –&gt;  runWorker –&gt;  getTask </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Worker.getTask方法源码</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> Runnable <span class="title">getTask</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">boolean</span> timedOut = <span class="keyword">false</span>; <span class="comment">// Did the last poll() time out?</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">        <span class="keyword">int</span> c = ctl.get();</span><br><span class="line">        <span class="keyword">int</span> rs = runStateOf(c);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Check if queue empty only if necessary.</span></span><br><span class="line">        <span class="keyword">if</span> (rs &gt;= SHUTDOWN &amp;&amp; (rs &gt;= STOP || workQueue.isEmpty())) &#123;</span><br><span class="line">            decrementWorkerCount();</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> wc = workerCountOf(c);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Are workers subject to culling?</span></span><br><span class="line">        <span class="comment">// 1.allowCoreThreadTimeOut变量默认是false,核心线程即使空闲也不会被销毁</span></span><br><span class="line">        <span class="comment">// 如果为true,核心线程在keepAliveTime内仍空闲则会被销毁。 </span></span><br><span class="line">        <span class="keyword">boolean</span> timed = allowCoreThreadTimeOut || wc &gt; corePoolSize;</span><br><span class="line">        <span class="comment">// 2.如果运行线程数超过了最大线程数，但是缓存队列已经空了，这时递减worker数量。 </span></span><br><span class="line">　　　　 <span class="comment">// 如果有设置允许线程超时或者线程数量超过了核心线程数量，</span></span><br><span class="line">        <span class="comment">// 并且线程在规定时间内均未poll到任务且队列为空则递减worker数量</span></span><br><span class="line">        <span class="keyword">if</span> ((wc &gt; maximumPoolSize || (timed &amp;&amp; timedOut))</span><br><span class="line">            &amp;&amp; (wc &gt; <span class="number">1</span> || workQueue.isEmpty())) &#123;</span><br><span class="line">            <span class="keyword">if</span> (compareAndDecrementWorkerCount(c))</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 3.如果timed为true(想想哪些情况下timed为true),则会调用workQueue的poll方法获取任务.</span></span><br><span class="line">            <span class="comment">// 超时时间是keepAliveTime。如果超过keepAliveTime时长，</span></span><br><span class="line">            <span class="comment">// poll返回了null，上边提到的while循序就会退出，线程也就执行完了。</span></span><br><span class="line">            <span class="comment">// 如果timed为false（allowCoreThreadTimeOut为falsefalse</span></span><br><span class="line">            <span class="comment">// 且wc &gt; corePoolSize为false），则会调用workQueue的take方法阻塞在当前。</span></span><br><span class="line">            <span class="comment">// 队列中有任务加入时，线程被唤醒，take方法返回任务，并执行。</span></span><br><span class="line">            Runnable r = timed ?</span><br><span class="line">                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :</span><br><span class="line">                workQueue.take();</span><br><span class="line">            <span class="keyword">if</span> (r != <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span> r;</span><br><span class="line">            timedOut = <span class="keyword">true</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException retry) &#123;</span><br><span class="line">            timedOut = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>核心线程的会一直卡在<code>workQueue.take</code>方法，被阻塞并挂起，不会占用CPU资源，直到拿到<code>Runnable</code> 然后返回（当然如果<strong>allowCoreThreadTimeOut</strong>设置为<code>true</code>,那么核心线程就会去调用<code>poll</code>方法，因为<code>poll</code>可能会返回<code>null</code>,所以这时候核心线程满足超时条件也会被销毁）。</p>
<p>非核心线程会workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) ，如果超时还没有拿到，下一次循环判断<strong>compareAndDecrementWorkerCount</strong>就会返回<code>null</code>,Worker对象的<code>run()</code>方法循环体的判断为<code>null</code>,任务结束，然后线程被系统回收 。</p>
</li>
</ol>
<h4 id="锁接口和类"><a href="#锁接口和类" class="headerlink" title="锁接口和类"></a>锁接口和类</h4><p>我们先来看看<code>synchronized</code>有什么不足之处。</p>
<ul>
<li>如果临界区是只读操作，其实可以多线程一起执行，但使用synchronized的话，<strong>同一时间只能有一个线程执行</strong>。</li>
<li>synchronized无法知道线程有没有成功获取到锁</li>
<li>使用synchronized，如果临界区因为IO或者sleep方法等原因阻塞了，而当前线程又没有释放锁，就会导致<strong>所有线程等待</strong>。</li>
</ul>
<p>而这些都是locks包下的锁可以解决的。</p>
<h5 id="锁的分类"><a href="#锁的分类" class="headerlink" title="锁的分类"></a>锁的分类</h5><ol>
<li><p>可重入锁和非可重入锁</p>
<p>支持重新进入的锁，也就是说这个锁支持一个<strong>线程对资源重复加锁</strong>。 递归调用。</p>
</li>
<li><p>公平锁与非公平锁</p>
<p>这里的“公平”，其实通俗意义来说就是“先来后到”，也就是FIFO。如果对一个锁来说，先对锁获取请求的线程一定会先被满足，后对锁获取请求的线程后被满足，那这个锁就是公平的。反之，那就是不公平的。 </p>
<p>一般情况下，<strong>非公平锁能提升一定的效率。但是非公平锁可能会发生线程饥饿（有一些线程长时间得不到锁）的情况</strong>。所以要根据实际的需求来选择非公平锁和公平锁。</p>
</li>
<li><p>读写锁和排它锁</p>
<p>我们前面讲到的synchronized用的锁和ReentrantLock，其实都是“排它锁”。也就是说，这些锁在同一时刻只允许一个线程进行访问。</p>
<p>而读写锁可以再同一时刻允许多个读线程访问。Java提供了ReentrantReadWriteLock类作为读写锁的默认实现，内部维护了两个锁：一个读锁，一个写锁。通过分离读锁和写锁，使得在“读多写少”的环境下，大大地提高了性能。</p>
</li>
</ol>
<h5 id="接口Condition-Lock-ReadWriteLock"><a href="#接口Condition-Lock-ReadWriteLock" class="headerlink" title="接口Condition/Lock/ReadWriteLock"></a>接口Condition/Lock/ReadWriteLock</h5><p> Lock接口里面有一些获取锁和释放锁的方法声明，而ReadWriteLock里面只有两个方法，分别返回“读锁”和“写锁”： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ReadWriteLock</span> </span>&#123;</span><br><span class="line">    <span class="function">Lock <span class="title">readLock</span><span class="params">()</span></span>;</span><br><span class="line">    <span class="function">Lock <span class="title">writeLock</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> Lock接口中有一个方法是可以获得一个<code>Condition</code>: </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">Condition <span class="title">newCondition</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>

<p> 之前我们提到了每个对象都可以用继承自<code>Object</code>的<strong>wait/notify</strong>方法来实现<strong>等待/通知机制</strong>。而Condition接口也提供了类似Object监视器的方法，通过与<strong>Lock</strong>配合来实现等待/通知模式。  Condition和Object的wait/notify基本相似。其中，Condition的await方法对应的是Object的wait方法，而Condition的<strong>signal/signalAll</strong>方法则对应Object的notify/notifyAll()。但Condition类似于Object的等待/通知机制的加强版。 </p>
<p> 如awaitNanos(long)，当前线程进入等待状态，直到被通知、中断或者超时。如果返回值小于等于0，可以认定就是超时了</p>
<h5 id="ReentrantLock"><a href="#ReentrantLock" class="headerlink" title="ReentrantLock"></a>ReentrantLock</h5><p>ReentrantLock是一个非抽象类，它是Lock接口的JDK默认实现，实现了锁的基本功能。从名字上看，它是一个”可重入“锁，从源码上看，它内部有一个抽象类<code>Sync</code>，是继承了AQS，自己实现的一个同步器。同时，ReentrantLock内部有两个非抽象类<code>NonfairSync</code>和<code>FairSync</code>，它们都继承了Sync。从名字上看得出，分别是”非公平同步器“和”公平同步器“的意思。这意味着ReentrantLock可以支持”公平锁“和”非公平锁“。 </p>
<h4 id="并发集合容器"><a href="#并发集合容器" class="headerlink" title="并发集合容器"></a>并发集合容器</h4><blockquote>
<p> java.util包下提供了一些容器类，而Vector和HashTable是线程安全的容器类，但是这些容器实现同步的方式是通过对方法加锁(sychronized)方式实现的，这样读写均需要锁操作，导致性能低下。 </p>
</blockquote>
<h5 id="ConcurrentMap接口"><a href="#ConcurrentMap接口" class="headerlink" title="ConcurrentMap接口"></a>ConcurrentMap接口</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">ConcurrentMap</span>&lt;<span class="title">K</span>, <span class="title">V</span>&gt; <span class="keyword">extends</span> <span class="title">Map</span>&lt;<span class="title">K</span>, <span class="title">V</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//插入元素</span></span><br><span class="line">    <span class="function">V <span class="title">putIfAbsent</span><span class="params">(K key, V value)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//移除元素</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">remove</span><span class="params">(Object key, Object value)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//替换元素</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">replace</span><span class="params">(K key, V oldValue, V newValue)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//替换元素</span></span><br><span class="line">    <span class="function">V <span class="title">replace</span><span class="params">(K key, V value)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h6 id="ConcurrentHashMap类"><a href="#ConcurrentHashMap类" class="headerlink" title="ConcurrentHashMap类"></a>ConcurrentHashMap类</h6><p>ConcurrentHashMap同HashMap一样也是基于散列表的map，但是它提供了一种与HashTable完全不同的加锁策略提供更高效的并发性和伸缩性。</p>
<p>ConcurrentHashMap提供了一种粒度更细的加锁机制来实现在多线程下更高的性能，这种机制叫分段锁(Lock Striping)。 就是<strong>将数据分段，对每一段数据分配一把锁</strong>。当一个线程占用锁访问其中一个段数据的时候，其他段的数据也能被其他线程访问。 有些方法需要跨段，比如size()、isEmpty()、containsValue()，它们可能需要锁定整个表而而不仅仅是某个段，这需要按顺序锁定所有段，操作完毕后，又按顺序释放所有段的锁。 </p>
<p><a href="https://my.oschina.net/hosee/blog/675884" target="_blank" rel="noopener">详见博客</a></p>
<h6 id="JDK1-7实现"><a href="#JDK1-7实现" class="headerlink" title="JDK1.7实现"></a>JDK1.7实现</h6><p>ConcurrentHashMap需要两个哈希操作来定位一个元素。第一个哈希查找Segement，第二个哈希查找元素所在的链表的头部。在这种结构下，哈希进程比普通的HashMap长，但是在那个时候的写操作，只有元素所在的段可以被锁定，并且它不会影响其他的段。理想情况下，ConcurrentHashMap可以同时支持写操作的段数， ConcurrentHashMap’s concurrency is improved. </p>
<img src="/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/concurrent-hashmap.png" class title="concurrent-hashmap">

<p> <img src="/java-notes/2020/05/25/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7/.%5CJava%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B-%E5%9F%BA%E7%A1%80-%E5%B7%A5%E5%85%B7%5Cconcurrent-hashmap.png" alt=" "> </p>
<ul>
<li><p>设计思路</p>
<ol>
<li><p>ConcurrentHashMap中的分段锁称为Segment，它即类似于HashMap的结构，即内部拥有一个Entry数组，数组中的每个元素又是一个链表 </p>
</li>
<li><p>Segment同时又是一个ReentrantLock（Segment继承了ReentrantLock） </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Segment</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; <span class="keyword">extends</span> <span class="title">ReentrantLock</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line">    <span class="comment">//HashEntry array that actually stores the data</span></span><br><span class="line">    <span class="keyword">transient</span> <span class="keyword">volatile</span> HashEntry&lt;K,V&gt;[] table;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//The number of elements in segemnt</span></span><br><span class="line">    <span class="keyword">transient</span> <span class="keyword">int</span> count;</span><br><span class="line"></span><br><span class="line">    / / The number of operations that affect the size of the table</span><br><span class="line">        <span class="keyword">transient</span> <span class="keyword">int</span> modCount;</span><br><span class="line"></span><br><span class="line">    / / threshold, the elements in the segment exceed <span class="keyword">this</span> value will expand</span><br><span class="line">        <span class="keyword">transient</span> <span class="keyword">int</span> threshold;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Load factor</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">float</span> loadFactor;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>HashEntry中的<strong>value以及next都被volatile修饰</strong>，这样在多线程读写过程中能够保持它们的可见性 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">HashEntry</span>&lt;<span class="title">K</span>,<span class="title">V</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> hash;</span><br><span class="line">    <span class="keyword">final</span> K key;</span><br><span class="line">    <span class="keyword">volatile</span> V value;</span><br><span class="line">    <span class="keyword">volatile</span> HashEntry&lt;K,V&gt; next;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
</li>
<li><p>初始化</p>
<p>每次put之前都需要检查key对应的Segment是否为null，如果是则调用ensureSegment()以确保对应的Segment被创建。ensureSegment可能在并发环境下被调用，但与想象中不同，ensureSegment并未使用锁来控制竞争，而是使用了Unsafe对象的getObjectVolatile()提供的原子读语义结合CAS来确保Segment创建的原子性。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> ((seg = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(ss, u))</span><br><span class="line">                == <span class="keyword">null</span>) &#123; <span class="comment">// recheck</span></span><br><span class="line">    Segment&lt;K,V&gt; s = <span class="keyword">new</span> Segment&lt;K,V&gt;(lf, threshold, tab);</span><br><span class="line">    <span class="keyword">while</span> ((seg = (Segment&lt;K,V&gt;)UNSAFE.getObjectVolatile(ss, u))</span><br><span class="line">           == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (UNSAFE.compareAndSwapObject(ss, u, <span class="keyword">null</span>, seg = s))</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>put/putIfAbsent/putAll</p>
<p>在获得锁之后，Segment对链表进行遍历，如果某个HashEntry节点具有相同的key，则更新该HashEntry的value值，否则新建一个HashEntry节点，将它设置为链表的新head节点并将原头节点设为新head的下一个节点。新建过程中如果节点总数（含新建的HashEntry）超过threshold，则调用rehash()方法对Segment进行扩容，最后将新建HashEntry写入到数组中。</p>
<p>put方法中，链接新节点的下一个节点（HashEntry.setNext()）以及将链表写入到数组中（setEntryAt()）都是通过Unsafe的putOrderedObject()方法来实现，这里并未使用具有原子写语义的putObjectVolatile()的原因是：JMM会保证获得锁到释放锁之间所有对象的状态更新都会在锁被释放之后更新到主存，从而保证这些变更对其他线程是可见的。</p>
</li>
<li><p>get与containsKey</p>
<p> get与containsKey两个方法几乎完全一致：他们都没有使用锁，而是通过Unsafe对象的getObjectVolatile()方法提供的原子读语义，来获得Segment以及对应的链表，然后对链表遍历判断是否存在key相同的节点以及获得该节点的value。但由于遍历过程中其他线程可能对链表结构做了调整，因此<strong>get和containsKey返回的可能是过时的数据，这一点是ConcurrentHashMap在弱一致性上的体现</strong>。如果要求强一致性，那么必须使用Collections.synchronizedMap()方法。 </p>
</li>
<li><p>size、containsValue</p>
<p>首先不加锁循环执行以下操作：循环所有的Segment（通过Unsafe的getObjectVolatile()以保证原子读语义），获得对应的值以及所有Segment的modcount之和。如果连续两次所有Segment的modcount和相等，则过程中没有发生其他线程修改ConcurrentHashMap的情况，返回获得的值。 </p>
<p>当循环次数超过预定义的值时，这时需要对所有的Segment依次进行加锁，获取返回值后再依次解锁。值得注意的是，加锁过程中要强制创建所有的Segment，否则容易出现其他线程创建Segment并进行put，remove等操作。代码如下： </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">int</span> j =<span class="number">0</span>; j &lt; segments.length; ++j)</span><br><span class="line">	ensureSegment(j).lock();<span class="comment">// force creation</span></span><br></pre></td></tr></table></figure>

<p>后，与HashMap不同的是，ConcurrentHashMap<strong>并不允许key或者value为null</strong>，按照Doug Lea的说法，这么设计的原因是在ConcurrentHashMap中，一旦value出现null，则代表HashEntry的key/value没有映射完成就被其他线程所见，需要特殊处理。 </p>
</li>
</ul>
<h6 id="JDK1-8实现"><a href="#JDK1-8实现" class="headerlink" title="JDK1.8实现"></a>JDK1.8实现</h6><p><a href="https://my.oschina.net/hosee/blog/675884" target="_blank" rel="noopener">ConcurrentHashMap在JDK8中进行了巨大改动，很需要通过源码来再次学习下Doug Lea的实现方法。</a></p>
<p>它摒弃了Segment（锁段）的概念，而是启用了一种全新的方式实现,利用CAS算法。它沿用了与它同时期的HashMap版本的思想，底层依然由“数组”+链表+红黑树的方式思想(<a href="http://my.oschina.net/hosee/blog/618953" target="_blank" rel="noopener">JDK7与JDK8中HashMap的实现</a>)，但是为了做到并发，又增加了很多辅助的类，例如TreeBin，Traverser等对象内部类。</p>
<h5 id="CopyOnWrite"><a href="#CopyOnWrite" class="headerlink" title="CopyOnWrite"></a>CopyOnWrite</h5><blockquote>
<p> 当有多个调用者同时去请求一个资源数据的时候，有一个调用者出于某些原因需要对当前的数据源进行修改，这个时候系统将会复制一个当前数据源的副本给调用者修改。 </p>
</blockquote>
<p>CopyOnWrite容器即<strong>写时复制的容器</strong>,当我们往一个容器中添加元素的时候，不直接往容器中添加，而是将当前容器进行copy，复制出来一个新的容器，然后向新容器中添加我们需要的元素，最后将原容器的引用指向新容器。 </p>
<p><strong>优点</strong>： CopyOnWriteArrayList经常被用于“读多写少”的并发场景，是因为CopyOnWriteArrayList无需任何同步措施，大大增强了读的性能。在Java中遍历线程非安全的List(如：ArrayList和 LinkedList)的时候，若中途有别的线程对List容器进行修改，那么会抛出<strong>ConcurrentModificationException</strong>异常。CopyOnWriteArrayList由于其”读写分离”，遍历和修改操作分别作用在不同的List容器，所以在使用迭代器遍历的时候，则不会抛出异常。 </p>
<p><strong>缺点：</strong> <strong>内存占用大</strong>，CopyOnWriteArrayList每次执行写操作都会将原容器进行拷贝了一份，数据量大的时候，内存会存在较大的压力，可能会引起频繁Full GC。<strong>时效性</strong> 写和读分别作用在不同新老容器上，在写操作执行过程中，读不会阻塞，但读取到的却是老容器的数据。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">add</span><span class="params">(E e)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ReentrantLock加锁，保证线程安全</span></span><br><span class="line">    <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">this</span>.lock;</span><br><span class="line">    lock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Object[] elements = getArray();</span><br><span class="line">        <span class="keyword">int</span> len = elements.length;</span><br><span class="line">        <span class="comment">// 拷贝原容器，长度为原容器长度加一</span></span><br><span class="line">        Object[] newElements = Arrays.copyOf(elements, len + <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 在新副本上执行添加操作</span></span><br><span class="line">        newElements[len] = e;</span><br><span class="line">        <span class="comment">// 将原容器引用指向新副本</span></span><br><span class="line">        setArray(newElements);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 解锁</span></span><br><span class="line">        lock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>案例：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Collection;</span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"><span class="keyword">import</span> java.util.Set;</span><br><span class="line"><span class="comment">// 我们来具体结合业务场景实现一个CopyOnWriteMap的并发容器并且来使用它。</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CopyOnWriteMap</span>&lt;<span class="title">K</span>, <span class="title">V</span>&gt; <span class="keyword">implements</span> <span class="title">Map</span>&lt;<span class="title">K</span>, <span class="title">V</span>&gt;, <span class="title">Cloneable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> Map&lt;K, V&gt; internalMap;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">CopyOnWriteMap</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        internalMap = <span class="keyword">new</span> HashMap&lt;K, V&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> V <span class="title">put</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            Map&lt;K, V&gt; newMap = <span class="keyword">new</span> HashMap&lt;K, V&gt;(internalMap);</span><br><span class="line">            V val = newMap.put(key, value);</span><br><span class="line">            internalMap = newMap;</span><br><span class="line">            <span class="keyword">return</span> val;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> V <span class="title">get</span><span class="params">(Object key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> internalMap.get(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">putAll</span><span class="params">(Map&lt;? extends K, ? extends V&gt; newData)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            Map&lt;K, V&gt; newMap = <span class="keyword">new</span> HashMap&lt;K, V&gt;(internalMap);</span><br><span class="line">            newMap.putAll(newData);</span><br><span class="line">            internalMap = newMap;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <strong>场景：</strong>假如我们有一个搜索的网站需要屏蔽一些“关键字”，“黑名单”每晚定时更新，每当用户搜索的时候，“黑名单”中的关键字不会出现在搜索结果当中，并且提示用户敏感字。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 黑名单服务</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlackListServiceImpl</span> </span>&#123;</span><br><span class="line">    <span class="comment">//　减少扩容开销。根据实际需要，初始化CopyOnWriteMap的大小，避免写时CopyOnWriteMap扩容的开销。</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> CopyOnWriteMap&lt;String, Boolean&gt; blackListMap = </span><br><span class="line">        <span class="keyword">new</span> CopyOnWriteMap&lt;String, Boolean&gt;(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">isBlackList</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> blackListMap.get(id) == <span class="keyword">null</span> ? <span class="keyword">false</span> : <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">addBlackList</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        blackListMap.put(id, Boolean.TRUE);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 批量添加黑名单</span></span><br><span class="line"><span class="comment">     * (使用批量添加。因为每次添加，容器每次都会进行复制，所以减少添加次数，可以减少容器的复制次数。</span></span><br><span class="line"><span class="comment">     * 如使用上面代码里的addBlackList方法)</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ids</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">addBlackList</span><span class="params">(Map&lt;String,Boolean&gt; ids)</span> </span>&#123;</span><br><span class="line">        blackListMap.putAll(ids);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="线程通信类"><a href="#线程通信类" class="headerlink" title="线程通信类"></a>线程通信类</h5><ol>
<li><p>CountDownLatch</p>
<p>CountDownLatch这个类的作用也很贴合这个名字的意义，假设某个线程在执行任务之前，需要等待其它线程完成一些前置任务，必须等所有的前置任务都完成，才能开始执行本线程的任务。 </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CountDownLatchDemo</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 定义前置任务线程</span></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">PreTaskThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">private</span> String task;</span><br><span class="line">        <span class="keyword">private</span> CountDownLatch countDownLatch;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">PreTaskThread</span><span class="params">(String task, CountDownLatch countDownLatch)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.task = task;</span><br><span class="line">            <span class="keyword">this</span>.countDownLatch = countDownLatch;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Random random = <span class="keyword">new</span> Random();</span><br><span class="line">                Thread.sleep(random.nextInt(<span class="number">1000</span>));</span><br><span class="line">                System.out.println(task + <span class="string">" - 任务完成"</span>);</span><br><span class="line">                countDownLatch.countDown();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 假设有三个模块需要加载</span></span><br><span class="line">        CountDownLatch countDownLatch = <span class="keyword">new</span> CountDownLatch(<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 主任务</span></span><br><span class="line">        <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">"等待数据加载..."</span>);</span><br><span class="line">                System.out.println(String.format(<span class="string">"还有%d个前置任务"</span>, countDownLatch.getCount()));</span><br><span class="line">                countDownLatch.await();</span><br><span class="line">                System.out.println(<span class="string">"数据加载完成，正式开始游戏！"</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 前置任务</span></span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> PreTaskThread(<span class="string">"加载地图数据"</span>, countDownLatch)).start();</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> PreTaskThread(<span class="string">"加载人物模型"</span>, countDownLatch)).start();</span><br><span class="line">        <span class="keyword">new</span> Thread(<span class="keyword">new</span> PreTaskThread(<span class="string">"加载背景音乐"</span>, countDownLatch)).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>等待数据加载… </p>
<p>还有3个前置任务 </p>
<p>加载人物模型 - 任务完成</p>
<p>加载背景音乐 - 任务完成 </p>
<p>加载地图数据 - 任务完成 </p>
<p>数据加载完成，正式开始游戏！ </p>
</blockquote>
<p>原理：内部类Sync最简单的实现AQS，初始化后每个线程结束后通过tryReleaseShared将标志位减一，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Sync</span> <span class="keyword">extends</span> <span class="title">AbstractQueuedSynchronizer</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">4982264981922014374L</span>;</span><br><span class="line"></span><br><span class="line">    Sync(<span class="keyword">int</span> count) &#123;</span><br><span class="line">        setState(count);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">getCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> getState();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">tryAcquireShared</span><span class="params">(<span class="keyword">int</span> acquires)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (getState() == <span class="number">0</span>) ? <span class="number">1</span> : -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">tryReleaseShared</span><span class="params">(<span class="keyword">int</span> releases)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Decrement count; signal when transition to zero</span></span><br><span class="line">        <span class="keyword">for</span> (;;) &#123;</span><br><span class="line">            <span class="keyword">int</span> c = getState();</span><br><span class="line">            <span class="keyword">if</span> (c == <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            <span class="keyword">int</span> nextc = c-<span class="number">1</span>;</span><br><span class="line">            <span class="keyword">if</span> (compareAndSetState(c, nextc))</span><br><span class="line">                <span class="keyword">return</span> nextc == <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// await将等待执行线程，加入到等待队列中。</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">await</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    sync.acquireSharedInterruptibly(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 其他前置线程执行完毕后，releaseShared方法最终调用tryReleaseShared</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">countDown</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    sync.releaseShared(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h5 id="Fork-Join"><a href="#Fork-Join" class="headerlink" title="Fork/Join"></a>Fork/Join</h5><blockquote>
<p> Fork/Join框架是一个实现了ExecutorService接口的多线程处理器，它专为那些可以通过递归分解成更细小的任务而设计，最大化的利用多核处理器来提高应用程序的性能。 </p>
</blockquote>
<p> <img src="https://gblobscdn.gitbook.com/assets%2F-L_5HvtIhTFW9TQlOF8e%2F-L_5TIKcBFHWPtY3OwUo%2F-L_5TJw4VyRYbSwAlVTD%2Ffork_join%E6%B5%81%E7%A8%8B%E5%9B%BE.png?alt=media" alt="img"></p>
<blockquote>
<p>工作窃取算法指的是在多线程执行不同任务队列的过程中，某个线程执行完自己队列的任务后从其他线程的任务队列里窃取任务来执行。 </p>
</blockquote>
<p>值得注意的是，当一个线程窃取另一个线程的时候，为了减少两个任务线程之间的竞争，我们通常使用<strong>双端队列</strong>来存储任务。被窃取的任务线程都从双端队列的<strong>头部</strong>拿任务执行，而窃取其他任务的线程从双端队列的<strong>尾部</strong>执行任务。 </p>
<p><strong>Fork/Join的具体实现</strong></p>
<p>通常情况下，在创建任务的时候我们一般不直接继承ForkJoinTask，而是继承它的子类<strong>RecursiveAction</strong>和<strong>RecursiveTask</strong>。两个都是ForkJoinTask的子类，<strong>RecursiveAction可以看做是无返回值的ForkJoinTask，RecursiveTask是有返回值的ForkJoinTask</strong>。</p>
<p><strong>ForkJoinPool</strong>是用于执行ForkJoinTask任务的执行（线程）池。ForkJoinPool管理着执行池中的线程和任务队列，此外，执行池是否还接受任务，显示线程的运行状态也是在这里处理。</p>
<p> WorkQueue双端队列，ForkJoinTask存放在这里。当工作线程在处理自己的工作队列时，会从队列尾取任务来执行（LIFO）；如果是窃取其他队列的任务时，窃取的任务位于所属任务队列的队首（FIFO）。ForkJoinPool与传统线程池最显著的区别就是它维护了一个<strong>工作队列数组</strong>（volatile WorkQueue[] workQueues，ForkJoinPool中的<strong>每个工作线程都维护着一个工作队列</strong>）。</p>
<p>使用Fork/Join实现快排</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">QuickSortForkJoin</span> <span class="keyword">extends</span> <span class="title">RecursiveAction</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] data;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> left;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> right;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">QuickSortForkJoin</span><span class="params">(<span class="keyword">int</span>[] data, <span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.data = data;</span><br><span class="line">        <span class="keyword">this</span>.left = left;</span><br><span class="line">        <span class="keyword">this</span>.right = right;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">compute</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (left &lt; right) &#123;</span><br><span class="line">            <span class="keyword">int</span> pivot = partition(data, left, right);</span><br><span class="line">            invokeAll(<span class="keyword">new</span> QuickSortForkJoin(data, left, pivot - <span class="number">1</span>),</span><br><span class="line">                    <span class="keyword">new</span> QuickSortForkJoin(data, pivot + <span class="number">1</span>, right));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">int</span> <span class="title">partition</span><span class="params">(<span class="keyword">int</span>[] data, <span class="keyword">int</span> left, <span class="keyword">int</span> right)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> pivotVal = data[left];</span><br><span class="line">        <span class="keyword">int</span> l = left;</span><br><span class="line">        <span class="keyword">int</span> r = right;</span><br><span class="line">        <span class="keyword">while</span> (l &lt; r) &#123;</span><br><span class="line">            <span class="keyword">while</span> (data[r] &gt;= pivotVal &amp;&amp; l &lt; r) &#123;</span><br><span class="line">                r--;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">while</span> (data[l] &lt;= pivotVal &amp;&amp; l &lt; r) &#123;</span><br><span class="line">                l++;</span><br><span class="line">            &#125;</span><br><span class="line">            swap(data, l, r);</span><br><span class="line">        &#125;</span><br><span class="line">        swap(data, left, l);</span><br><span class="line">        <span class="keyword">return</span> l;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">swap</span><span class="params">(<span class="keyword">int</span>[] data, <span class="keyword">int</span> a, <span class="keyword">int</span> b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> temp = data[a];</span><br><span class="line">        data[a] = data[b];</span><br><span class="line">        data[b] = temp;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> count = <span class="number">10000</span>;</span><br><span class="line">        <span class="keyword">int</span>[] data = <span class="keyword">new</span> <span class="keyword">int</span>[count];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = count; i &gt; <span class="number">0</span>; i--) &#123;</span><br><span class="line">            data[i - <span class="number">1</span>] = (<span class="keyword">int</span>) (Math.random() * count);</span><br><span class="line">        &#125;</span><br><span class="line">        ForkJoinPool forkJoinPool = <span class="keyword">new</span> ForkJoinPool();</span><br><span class="line">        Future&lt;Void&gt; result = forkJoinPool.submit(<span class="keyword">new</span> QuickSortForkJoin(data, <span class="number">0</span>, count - <span class="number">1</span>));</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            result.get();</span><br><span class="line">            System.out.println(Arrays.toString(data));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ExecutionException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="Java-8-Stream并行计算"><a href="#Java-8-Stream并行计算" class="headerlink" title="Java 8 Stream并行计算"></a>Java 8 Stream并行计算</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StreamParallelDemo</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>)</span><br><span class="line">                .parallel()</span><br><span class="line">                .reduce((a, b) -&gt; &#123;</span><br><span class="line">                    System.out.println(String.format(<span class="string">"%s: %d + %d = %d"</span>,</span><br><span class="line">                            Thread.currentThread().getName(), a, b, a + b));</span><br><span class="line">                    <span class="keyword">return</span> a + b;</span><br><span class="line">                &#125;)</span><br><span class="line">                .ifPresent(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>ForkJoinPool.commonPool-worker-1: 3 + 4 = 7 ForkJoinPool.commonPool-worker-4: 8 + 9 = 17 ForkJoinPool.commonPool-worker-2: 5 + 6 = 11 ForkJoinPool.commonPool-worker-3: 1 + 2 = 3 ForkJoinPool.commonPool-worker-4: 7 + 17 = 24 ForkJoinPool.commonPool-worker-4: 11 + 24 = 35 ForkJoinPool.commonPool-worker-3: 3 + 7 = 10 ForkJoinPool.commonPool-worker-3: 10 + 35 = 45 </p>
<p>45 </p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/java-notes/tags/JavaSE/" rel="tag"># JavaSE</a>
          
            <a href="/java-notes/tags/Concurrent/" rel="tag"># Concurrent</a>
          
            <a href="/java-notes/tags/Atomic/" rel="tag"># Atomic</a>
          
            <a href="/java-notes/tags/Thread/" rel="tag"># Thread</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/java-notes/2020/04/19/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="next" title="Java并发编程(原理)">
                <i class="fa fa-chevron-left"></i> Java并发编程(原理)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/java-notes/2020/05/25/JavaSe%E5%B8%B8%E8%A7%81%E9%9D%A2%E8%AF%95/" rel="prev" title="JavaSe常见面试">
                JavaSe常见面试 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">HitoMeng</p>
              <p class="site-description motion-element" itemprop="description">You do have the time!</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/java-notes/archives/%7C%7Carchive">
              
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/java-notes/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/java-notes/tags/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#基础知识"><span class="nav-number">1.</span> <span class="nav-text">基础知识</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#概念"><span class="nav-number">1.1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#入门类及接口"><span class="nav-number">1.2.</span> <span class="nav-text">入门类及接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程状态转换"><span class="nav-number">1.3.</span> <span class="nav-text">线程状态转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程间通讯"><span class="nav-number">1.4.</span> <span class="nav-text">线程间通讯</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#工具"><span class="nav-number">2.</span> <span class="nav-text">工具</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#线程池"><span class="nav-number">2.0.1.</span> <span class="nav-text">线程池</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#线程池原理"><span class="nav-number">2.0.1.1.</span> <span class="nav-text">线程池原理</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#锁接口和类"><span class="nav-number">2.0.2.</span> <span class="nav-text">锁接口和类</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#锁的分类"><span class="nav-number">2.0.2.1.</span> <span class="nav-text">锁的分类</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#接口Condition-Lock-ReadWriteLock"><span class="nav-number">2.0.2.2.</span> <span class="nav-text">接口Condition&#x2F;Lock&#x2F;ReadWriteLock</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#ReentrantLock"><span class="nav-number">2.0.2.3.</span> <span class="nav-text">ReentrantLock</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#并发集合容器"><span class="nav-number">2.0.3.</span> <span class="nav-text">并发集合容器</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#ConcurrentMap接口"><span class="nav-number">2.0.3.1.</span> <span class="nav-text">ConcurrentMap接口</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#ConcurrentHashMap类"><span class="nav-number">2.0.3.1.1.</span> <span class="nav-text">ConcurrentHashMap类</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#JDK1-7实现"><span class="nav-number">2.0.3.1.2.</span> <span class="nav-text">JDK1.7实现</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#JDK1-8实现"><span class="nav-number">2.0.3.1.3.</span> <span class="nav-text">JDK1.8实现</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#CopyOnWrite"><span class="nav-number">2.0.3.2.</span> <span class="nav-text">CopyOnWrite</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#线程通信类"><span class="nav-number">2.0.3.3.</span> <span class="nav-text">线程通信类</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Fork-Join"><span class="nav-number">2.0.3.4.</span> <span class="nav-text">Fork&#x2F;Join</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#Java-8-Stream并行计算"><span class="nav-number">2.0.3.5.</span> <span class="nav-text">Java 8 Stream并行计算</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HitoMeng</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/java-notes/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/java-notes/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/java-notes/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/java-notes/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/java-notes/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/java-notes/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/java-notes/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/java-notes/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/java-notes/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
